<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />

    <!-- 头像区域 -->
    <div class="avatar-box">
      <van-image :src="userInfo.photo" round fit="cover" />
      <van-uploader :after-read="afterRead" />
    </div>

    <!-- 三个cell-资料区域 -->
    <van-cell-group>
      <van-cell
        @click="changeName"
        title="名称"
        :value="userInfo.name"
        is-link
      />
      <van-cell
        @click="genderShow = true"
        title="性别"
        :value="userInfo.gender ? '女' : '男'"
        is-link
      />
      <van-cell @click="clickBirthCell" title="生日" :value="userInfo.birthday" is-link />
    </van-cell-group>

    <!-- 裁剪容器盒子 -->
    <div class="crop-box" v-show="cropShow">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="200"
        autoCropHeight="200"
      ></vueCropper>

      <van-button @click="doCrop" type="primary">裁剪</van-button>
      <van-button @click="cropShow = false" style="right:0;" type="primary"
        >取消</van-button
      >
    </div>

    <!-- 修改昵称的弹出框 -->
    <!-- v-model绑定它是否显示 -->
    <van-dialog
      @confirm="confirmName"
      v-model="nameShow"
      title="修改昵称"
      show-cancel-button
    >
      <van-field ref="name" v-model="inpName" />
    </van-dialog>

    <!-- 修改性别的弹出层 -->
    <van-popup v-model="genderShow" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="genderShow = false"
      />
      <van-cell @click="changeGender(0)" title="男" is-link />
      <van-cell @click="changeGender(1)" title="女" is-link />
    </van-popup>

    <van-popup v-model="birthShow" position="bottom">
      <!--
        v-model绑定的currentDate是用来双向绑定当前时间
           可以设置它默认显示的时间，以及你选择的时间变了，这个值也会跟着变
        min-date最小可选时间
        max-date最大可选时间
       -->
      <van-datetime-picker
        @cancel="birthShow = false"
        @confirm="changeBirth"
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { VueCropper } from 'vue-cropper'
import { avatarAPI, editUserInfoAPI } from '@/api/user'
import dayjs from 'dayjs'
export default {
  components: {
    VueCropper
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  async created () {
    // 1. 调用actions来发请求
    this.$store.dispatch('user/reqUserInfo')
  },
  data () {
    return {
      cropShow: false,
      cropImg: '',
      nameShow: false,
      inpName: '',
      genderShow: false,
      birthShow: false,
      minDate: new Date('1949-10-1'),
      maxDate: new Date(),
      currentDate: new Date(2021, 0, 17)
    }
  },
  methods: {
    // 点击确认修改生日
    async changeBirth () {
      // 先把选择的时间对象转成YYYY-MM-DD的字符串
      const birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
      // 发请求
      await editUserInfoAPI({
        birthday
      })
      // 修改到本地
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        birthday
      })
      // 隐藏弹出层
      this.birthShow = false
    },
    // 点击了生日的cell
    clickBirthCell () {
      // 显示出生日弹出层
      this.birthShow = true
      // 把当前生日赋值给currentDate
      this.currentDate = new Date(this.userInfo.birthday)
    },
    // 修改性别
    async changeGender (gender) {
      // 发请求
      await editUserInfoAPI({
        gender
      })
      // 修改本地
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        gender
      })
      // 隐藏弹出层
      this.genderShow = false
    },
    afterRead (file) {
      // 当我们选择完一张文件后触发
      // 此时可以自行将文件上传至服务器
      // 这个参数里有个属性叫content，就是得到我们选中的图片的base64
      // console.log(file)
      this.cropShow = true
      this.cropImg = file.content
    },

    doCrop () {
      // 1. 获取裁剪后的内容
      this.$refs.cropper.getCropBlob(async data => {
        // 上传头像要用FormData
        const fd = new FormData()
        fd.append('photo', data)
        // 发请求就发fd
        const res = await avatarAPI(fd)
        // 隐藏裁剪容器
        this.cropShow = false
        // 更新头像
        this.$store.commit('user/setUserInfo', {
          ...this.userInfo,
          photo: res.data.photo
        })
      })
    },

    // 修改名字
    changeName () {
      // 1. 显示出弹出框 --- dom还没渲染，就意味着还没有输入框
      this.nameShow = true
      // 2. 把当前昵称赋值到输入框
      this.inpName = this.userInfo.name
      this.$nextTick(() => {
        // 3. 让输入框获得焦点
        this.$refs.name.focus()
      })
    },

    async confirmName () {
      // 非空判断
      if (this.inpName === '') return this.$toast('请输入内容')
      // 1. 发请求给服务器
      await editUserInfoAPI({
        name: this.inpName
      })

      // 2. 更新界面 -- 修改vuex里的数据
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        name: this.inpName
      })
    }
  }
}
</script>

<style scoped lang="less">
.avatar-box {
  @h: 140px;
  height: @h;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .van-image {
    width: 120px;
    height: 120px;
  }

  .van-uploader {
    position: absolute;
    left: 0;
    top: 0;

    ::v-deep .van-uploader__upload {
      position: absolute;
      left: 0;
      top: 0;
      width: 100vw;
      height: @h;
      opacity: 0;
    }
  }
}

.crop-box {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;

  .van-button {
    position: absolute;
    bottom: 0;
  }
}

.van-field {
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
</style>
